package com.googlecode.utterlyidle.multipart;

import com.googlecode.totallylazy.Callable2;

import java.nio.ByteBuffer;

import static com.googlecode.totallylazy.Callables.length;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.totallylazy.numbers.Numbers.sum;

public class ByteArrays {
    public static byte[] combine(byte[]... arrays) {
        Number length = sequence(arrays).map(length()).reduce(sum());
        ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[length.intValue()]);
        return sequence(arrays).fold(byteBuffer, addToBuffer()).array();
    }

    static Callable2<ByteBuffer, byte[], ByteBuffer> addToBuffer() {
        return new Callable2<ByteBuffer, byte[], ByteBuffer>() {
            @Override
            public ByteBuffer call(ByteBuffer byteBuffer, byte[] bytes) throws Exception {
                return byteBuffer.put(bytes);
            }
        };
    }
}
